package io.gitee.hechenl.easyopc.config;

import io.gitee.hechenl.easyopc.opcua.*;
import io.gitee.hechenl.easyopc.service.ICacheService;
import io.gitee.hechenl.easyopc.service.ITestDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;
import java.util.List;

@Configuration
public class OpcUaConfig {

    @Value("${opcua.server.url8}")
    private String url8;

    @Value("${opcua.server.url9}")
    private String url9;

    @Autowired
    private ICacheService opcUaDataService;
    @Autowired
    private ITestDataService opcUaTestService;

    /**所有可访问的节点*/
    @Bean
    public List<EasyNodeId> accessNodeIdList() {
        return Arrays.asList(
                new EasyNodeId(url8, EasyOpcUaUtil.convertNodeId(2, opcUaTestService.getIdentifiers8())),
                new EasyNodeId(url9, EasyOpcUaUtil.convertNodeId(2, opcUaTestService.getIdentifiers9()))
        );
    }

    /**要订阅的节点*/
    @Bean
    public List<EasyNodeId> subscriptNodeIdList() {
        return Arrays.asList(
                new EasyNodeId(url8, EasyOpcUaUtil.convertNodeId(2, opcUaTestService.getIdentifiers8())),
                new EasyNodeId(url9, EasyOpcUaUtil.convertNodeId(2, opcUaTestService.getIdentifiers9()))
        );
    }

    @Bean
    public EasyNodeIdProvider nodeIdProvider() {
        return new EasyNodeIdProvider() {
            @Override
            public List<EasyNodeId> getAccessNodeIdList() {
                return accessNodeIdList();
            }
            @Override
            public List<EasyNodeId> getSubscriptNodeIdList() {
                return subscriptNodeIdList();
            }
        };
    }

    @Bean
    public EasyNodeIdContext opcUaNodeIdContext(EasyNodeIdProvider easyNodeIdProvider) {
        return new EasyNodeIdContext(easyNodeIdProvider);
    }

    @Bean
    public EasyOpcUaClient easyOpcUaClient(
            @Value("${opcua.client.appName}")String appName,
            @Value("${opcua.client.appUri}")String appUri,
            EasyNodeIdContext easyNodeIdContext) {
        return new EasyOpcUaClient(
                appName,
                appUri,
                true,
                easyNodeIdContext,
                (clientName, nodeId, variant)
                        -> opcUaDataService.cache(
                                String.valueOf(nodeId.getIdentifier()),
                        String.valueOf(variant.getValue()))
        );
    }

}
